import numpy as np
import cv2
from matplotlib import pyplot as plt

# built-in modules
import sys

# local modules
import video

import logging


def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    # handler = logging.FileHandler('log.txt', mode='w')
    # handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger


logger = setup_custom_logger('app')

if __name__ == '__main__':
    path1 = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/201809-光辉之门.png'
    path2 = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/201809-光辉之门-2.png'

    # path1 = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/201809-微风平原.png'
    # path2 = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/201809-微风平原-2.png'

    img1 = cv2.imread(path1)
    img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)

    img2 = cv2.imread(path2)
    img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)

    # img_diff = img1 - img2
    img_diff = cv2.absdiff(img1, img2)
    # img_diff2 = img2 - img1
    img_diff2 = cv2.subtract(img1, img2)

    FILTER_MIN = np.array([20, 20, 20], np.uint8)
    FILTER_MAX = np.array([255, 255, 255], np.uint8)
    frame_threshed = cv2.inRange(img_diff, FILTER_MIN, FILTER_MAX)
    kernel_erode = np.ones((3, 3), np.uint8)
    kernel_dilate = np.ones((5, 5), np.uint8)
    frame_threshed2 = cv2.erode(frame_threshed, kernel_erode, iterations=1)
    frame_threshed2 = cv2.dilate(frame_threshed2, kernel_dilate, iterations=4)

    image, contours, hierarchy = cv2.findContours(frame_threshed2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]
    canvas = np.zeros(frame_threshed2.shape, np.uint8)
    img_c = cv2.drawContours(canvas, contours, -1, (0, 255, 0), 3)

    # edges = cv2.Canny(frame_threshed2, 50, 200)
    # frame_threshed2 = cv2.morphologyEx(frame_threshed2, cv2.MORPH_CLOSE, kernel_close)
    img_diff2 = cv2.bitwise_or(img2, img2, mask=frame_threshed)

    # plt.subplot(221), plt.imshow(img1)
    # plt.subplot(222), plt.imshow(img2)
    # plt.subplot(223), plt.imshow(img_diff)
    # plt.subplot(224), plt.imshow(img_diff2)

    plt.subplot(221), plt.imshow(img2)
    plt.subplot(222), plt.imshow(frame_threshed)
    plt.subplot(223), plt.imshow(frame_threshed2)
    plt.subplot(224), plt.imshow(img_c)
    # plt.subplot(224), plt.imshow(img_diff2)

    plt.show()

    sys.exit()
